<template>
  <el-dialog
    width="20%"
    title="修改密码"
    :visible.sync="pwdDialog"
    :show-close="false"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form :model="pwd" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="旧密码" prop="oldPwd">
        <el-input v-model="pwd.oldPwd" show-password></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPwd">
        <el-input v-model="pwd.newPwd" show-password></el-input>
      </el-form-item>
      <!-- <el-form-item> -->
      <!-- </el-form-item> -->
    </el-form>
    <div slot="footer">
        <el-button @click="closeHandler()">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">修改密码</el-button>
      </div>
  </el-dialog>
</template>
<script>
export default {
  props: {
    dialog: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    dialog() {
      this.pwdDialog = this.dialog;
    }
  },
  data() {
    return {
      pwd: {
        oldPwd: null,
        newPwd: null,
        phone: null
      },
      rules: {
        oldPwd: [
          { required: true, message: "请输入旧密码", trigger: "blur" },
          { min: 8, max: 12, message: "长度在 8 到 12 个字符", trigger: "blur" }
        ],
        newPwd: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          { min: 8, max: 12, message: "长度在 8 到 12 个字符", trigger: "blur" }
        ]
      },
      pwdDialog: false
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.updatePwd();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    updatePwd: function() {
      let this_ = this;
      var user = JSON.parse(sessionStorage.getItem("user"));
      this.pwd.phone = user.phone;

      var md5 = require("md5");
      this.pwd.oldPwd = md5(this.pwd.oldPwd);
      this.pwd.newPwd = md5(this.pwd.newPwd);

      this.axios
        .post("/fc/user/update", this.pwd)
        .then(response => {
          if (response.data.code == 200) {
            this.$router.push("/login");
          } else if (response.data.code == 201) {
            this.$alert("账号或密码错误", "错误提示", {
              confirmButtonText: "确定",
              callback: action => {}
            });
          }
        })
        .catch(response => {
          console.log("response -   " + response);
        });
    },
    // 关闭
    closeHandler: function() {
      this.pwd = {
        oldPwd: null,
        newPwd: null,
        phone: null
      };
      this.$emit("close");
    }
  }
};
</script>
